﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Admin_ManageRoles : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Roles.IsUserInRole(Membership.GetUser().UserName, "Admin"))
                Response.Redirect("~/");
        }
        catch
        {
            Response.Redirect("~/");
        }

        if (!IsPostBack)
            BindRoles();
    }

    private void BindRoles()
    {
        LMSData.RoleCollection rc = new LMSData.RoleCollection();
        SubSonic.Query qry = new SubSonic.Query(LMSData.Role.Schema).WHERE(LMSData.Role.Columns.IsDeleted, false);
        rc.LoadAndCloseReader(qry.ExecuteReader());

        grdRoles.DataSource = rc;
        grdRoles.DataBind();
    }

    protected void AddNewRole(object sender, EventArgs e)
    {
        if (!Roles.RoleExists(txtRoleName.Text))
        {
            Roles.CreateRole(txtRoleName.Text);
            BindRoles();
            ModalPopup1.Hide();
        }
        else
            lblStatus.Text = "Role Name Already Exists";

        update1.Update();
    }

    protected void DeleteRole(object sender, CommandEventArgs e)
    {
        LMSData.Role rl = new LMSData.Role(e.CommandArgument.ToString());
        Roles.DeleteRole(rl.RoleName, false);

        BindRoles();
        update1.Update();
    }

    protected void OpenEditRole(object sender, CommandEventArgs e)
    {
        hidRoleID.Value = e.CommandArgument.ToString();
        txtEditRoleName.Text = new LMSData.Role(e.CommandArgument.ToString()).RoleName;
        EditRolePopupExtender.ShowAt((Control)sender);
    }

    protected void EditRole(object sender, EventArgs e)
    {
        LMSData.Role rl = new LMSData.Role(hidRoleID.Value);
        if (!Roles.RoleExists(txtEditRoleName.Text))
        {
            rl.RoleName = txtEditRoleName.Text;
            rl.Save();

            EditRolePopupExtender.Hide();
            BindRoles();
        }
        else
            lblStatus.Text = "Role Name Already Exists";

        update1.Update();
    }

    protected void pnlEditRoleClose(object sender, EventArgs e)
    {
        EditRolePopupExtender.Hide();
    }
}
